#include "yuvplayer.h"
#include <QPainter>
#include "ffmpegutil.h"
YUVPlayer::YUVPlayer(QWidget *parent) : QWidget(parent)
{

    setAttribute(Qt::WA_StyledBackground);
    setStyleSheet("background:black");
}

YUVPlayer::~YUVPlayer()
{

    if(_yuvSpec) {

        delete _yuvSpec;
        _yuvSpec = nullptr;
    }

    if(_yuvFile) {

        _yuvFile->close();
        delete _yuvFile;
        _yuvFile = nullptr;
    }

    if(_imageBuffer) {

        delete [] _imageBuffer;
        _imageBuffer = nullptr;
    }

    if(_timer > 0) {

        killTimer(_timer);
        _timer = 0;
    }

    if(_paintImage) {

        delete [] _paintImage->bits();
        delete _paintImage;
        _paintImage = nullptr;
    }
}

int YUVPlayer::init(YUVFileSpec &yuvSpec)
{

    _yuvSpec = new YUVFileSpec(yuvSpec);

    _yuvFile = new QFile(_yuvSpec->getYuvPath());

    if(!_yuvFile->open(QFile::ReadOnly)){

        _yuvFile = nullptr;
        return 1;
    }


    _imageBuffer = new char[_yuvSpec->imageSize()];

    return 0;
}


void YUVPlayer::play()
{

    if(_timer > 0) {

        killTimer(_timer);
    }
    _timer = startTimer(1000.0 / _yuvSpec->getFps());
    _state = Playing;
}

void YUVPlayer::timerEvent(QTimerEvent *event)
{
   int len = _yuvFile->read(_imageBuffer,_yuvSpec->imageSize());
   qDebug() << "len " << len;
   if(len > 0) {

       // yuv 转 rgb

//       _paintImage = new QImage()
    YUVDataSpec inDataSpec(_yuvSpec->getWidth(),_yuvSpec->getHeight(),_yuvSpec->getFps(),_yuvSpec->getFormat(),_imageBuffer);
    YUVDataSpec outDataSpec(_yuvSpec->getWidth(),_yuvSpec->getHeight(),_yuvSpec->getFps(),AV_PIX_FMT_RGB24,nullptr);

    if(_paintImage){

        delete [] _paintImage->bits();
        _paintImage = nullptr;
    }

    FFmpegUtil::yuvToRGB(inDataSpec,outDataSpec);

    _paintImage = new QImage((uchar*)outDataSpec.getData(),outDataSpec.getWidth(),outDataSpec.getHeight(),QImage::Format_RGB888);

    update();
   }else{

       killTimer(_timer);
       _timer = 0;
   }
}

void YUVPlayer::paintEvent(QPaintEvent *event)
{
    if(_paintImage == nullptr) {

        return;
    }


    int x = 0,y = 0,paintWidth = _paintImage->width(), paintHeight = _paintImage->height();


    if(paintWidth > width() || paintHeight > height()) {


        if(height() * paintWidth < width()* paintHeight) {

            paintWidth = (paintWidth * 1.0 / paintHeight) * height();
            paintHeight = height();
        }else {
            paintHeight = (paintHeight * 1.0 / paintWidth) * width();
            paintWidth = width();
        }
    }

    x = (width() - paintWidth) >> 1;
    y = (height() - paintHeight) >> 1;
    QRect rect(x,y,paintWidth,paintHeight);
    QPainter(this).drawImage(rect,*_paintImage);
}


















